<template>
  <div class="time-line-wrap" data-left-number="450px">
    <div class="time-wrap">
      <div class="retreat" @click="retreat()">
        <span class="iconfont icon-fanhui"></span>
      </div>
      <div class="play suspend" @click="play()">
        <span
          class="iconfont"
          :class="timerId ? 'icon-bofangqi-zanting' : 'icon-bofangqi-bofang'"
        ></span>
      </div>
      <div class="forward" @click="forward()">
        <span class="iconfont icon-fanhui"></span>
      </div>
      <div :disabled="isFirstPage" class="prev" @click="previousPage">
        <span class="iconfont icon-fanhui"></span>
      </div>
      <div class="time-ticp-wrap">
        <el-scrollbar
          ref="scrollbar"
          wrap-class="scroll-wrap"
          view-class="scroll-view"
        >
          <div class="time-ticp">
            <div
              v-for="(item, index) in computedTimeValue"
              :key="index"
              class="item-wrap"
              @click="changeCurrentTime(index)"
            >
              <div :class="item.name ? 'name1' : 'name2'">{{ item.name }}</div>
              <div class="item" :class="[index === timeIndex && 'active']">
                {{ item.value }}
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <div :disabled="isLastPage" class="next" @click="nextPage">
        <span class="iconfont icon-fanhui"></span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { useTrafficStore } from '@/pages/traffic/store/store'

const trafficStore = useTrafficStore()

// 当前时间索引 默认0
const timeIndex = computed({
  get() {
    return trafficStore.timeIndex
  },
  set(val) {
    trafficStore.timeIndex = val
  }
})
// 时间队列 固定24条
const timeArr = computed(() => trafficStore.timeList)

// const now = dayjs()
// for (let i = 0; i < 24; i++) {
//   timeArr.value.push(now.add(i, 'hour').format('YYYY-MM-DD HH:00:00'))
// }

const timerId = ref('') // 播放定时器
// let timeIndex = inject('timeIndex') //当前下标
// let timeArr = ref([
//   //时间轴数据
//   '2023-11-05 08:00:00',
//   '2023-11-05 20:00:00',
//   '2023-11-06 08:00:00',
//   '2023-11-06 20:00:00'
// ])
const timeCurrent = ref('') // 当前选中项的内容
useEventBus('update:timeLine').on(data => {
  // 接口获取完成之后  需要触发下这个bus  修改时间轴的数据
  if (data && data.length !== 0) {
    timeArr.value = []
    data.forEach(item => {
      timeArr.value.push(item.reportTime)
    })
  }
})
const computedTimeValue = computed(() => {
  const arr = []
  timeArr.value.forEach((element, index) => {
    arr.push({
      day: element,
      name: getTimeName(arr, element, index),
      value: dayjs(element).format('HH')
    })
  })
  return arr
})
const getTimeName = (arr, element, index) => {
  if (index == 0) {
    return `${dayjs(element).format('DD')}日`
  } else {
    if (arr[index - 1].name == '') {
      if (
        dayjs(arr[index - 1].day).format('DD') == dayjs(element).format('DD')
      ) {
        return ''
      } else {
        return `${dayjs(element).format('DD')}日`
      }
    } else {
      if (arr[index - 1].name == `${dayjs(element).format('DD')}日`) {
        return ''
      } else {
        return `${dayjs(element).format('DD')}日`
      }
    }
    return `${dayjs(element).format('DD')}日`
  }
}
const scrollbar = ref(null) // el-scrollbar组件的引用
const currentPage = ref(1) // 当前页码
const pageSize = ref(8) // 每页显示的数量

const totalPages = computed(() => {
  // 计算总页数
  return Math.ceil(computedTimeValue.value.length / pageSize.value)
})

const displayedItems = computed(() => {
  // 计算当前页显示的数据
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return computedTimeValue.value.slice(start, end)
})

const isFirstPage = computed(() => {
  // 判断是否处于起始位置
  return currentPage.value === 1
})

const isLastPage = computed(() => {
  // 判断是否处于末尾位置
  return currentPage.value === totalPages.value
})
const previousPage = () => {
  if (!isFirstPage.value) {
    currentPage.value--
  } else {
    scrollbar.value.scrollTo(0, 0)
  }
}

const nextPage = () => {
  if (!isLastPage.value) {
    currentPage.value++
  }
}
const scrollToPosition = currentPage => {
  const index = (currentPage - 1) * pageSize.value // 第二个项目的索引
  const itemHWidth = 46 // 每个项目的宽度
  const position = index * itemHWidth // 计算滚动条的位置
  scrollbar.value.scrollTo(position, 0) // 滚动到指定位置
}
timeCurrent.value = {
  time: `${computedTimeValue.value[timeIndex.value].day} ${
    computedTimeValue.value[timeIndex.value].value
  }`
}
watch(currentPage, (newData, oldData) => {
  if (newData != oldData) scrollToPosition(newData)
})
watch(timeIndex, (newData, oldData) => {
  if (newData != oldData)
    timeCurrent.value = {
      time: `${computedTimeValue.value[timeIndex.value].day} ${
        computedTimeValue.value[timeIndex.value].value
      }`
    }
})
const play = () => {
  // 播放暂停按钮
  if (computedTimeValue.length < 2) return
  if (!timerId.value) {
    playTimer()
  } else {
    closeplay()
  }
}
const closeplay = () => {
  // 关闭播放
  clearInterval(timerId.value)
  timerId.value = null
}
const playTimer = () => {
  // 执行播放定时器
  timerId.value = setInterval(() => {
    timeIndex.value += 1
    if (timeIndex.value === computedTimeValue.value.length) {
      timeIndex.value = 0
      closeplay()
    }
    currentPage.value = Math.ceil(timeIndex.value / 8)
  }, 1000)
}
const retreat = () => {
  // 退后一个
  // 先清除定时器 修改当前下标 重新执行定时器
  const flag = timerId.value
  if (flag) clearInterval(timerId.value)
  if (timeIndex.value === 0)
    timeIndex.value = computedTimeValue.value.length - 1
  else timeIndex.value -= 1
  if (flag) playTimer()
  currentPage.value = Math.ceil(timeIndex.value / 8)
}
const forward = () => {
  // 前进一个
  // 先清除定时器 修改当前下标 重新执行定时器
  const flag = timerId.value
  if (flag) clearInterval(timerId.value)
  if (timeIndex.value === computedTimeValue.value.length - 1)
    timeIndex.value = 0
  else timeIndex.value += 1
  if (flag) playTimer()
  currentPage.value = Math.ceil(timeIndex.value / 8)
}
const changeCurrentTime = index => {
  const flag = timerId.value
  if (flag) clearInterval(timerId.value)
  timeIndex.value = index
  if (flag) playTimer()
}
onUnmounted(() => {
  if (timerId.value) clearInterval(timerId.value)
  timeIndex.value = 0
  timerId.value = null
})
</script>

<style lang="scss" scoped>
.time-line-wrap {
  --left-number: calc(var(--left-number-value) * 1px);
  position: absolute;
  left: calc(50% - var(--left-number));
  top: 10px;
  width: 585px;
  height: 51px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 4px 4px 4px 4px;
  z-index: 1200;
  cursor: default;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 0 15px;
  font-size: 16px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  color: #ffffff;
  transition: all 0.5s;
  background: rgba(0, 13, 35, 0.76);
  box-shadow: 0px 0px 6px 1px rgba(0, 204, 255, 0.77),
    inset 0px 0px 14px 1px #00ccff;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #2c96cd;
  .btn-type-wrap {
    background: #dadada;
    border-radius: 23px 23px 23px 23px;
    padding: 4px 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    .btn-type-item {
      background: none;
      cursor: pointer;
      color: #000;
      padding: 4px 15px;
      &.active {
        background: #4056cc;
        color: #fff;
        border-radius: 22px 22px 22px 22px;
      }
    }
  }
  .time-wrap {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-left: 5px;
    overflow: hidden;
    .retreat {
      width: 24px;
      height: 24px;
      background: #4056cc;
      margin: 0 5px;
      cursor: pointer;
      color: #fff;
      font-size: 14px;
      text-align: center;
      line-height: 24px;
    }
    .play {
      width: 24px;
      height: 24px;
      background: #4056cc;
      margin: 0 5px;
      cursor: pointer;
      color: #fff;
      font-size: 14px;
      text-align: center;
      line-height: 24px;
    }
    .suspend {
      width: 24px;
      height: 24px;
      background: #4056cc;
      margin: 0 5px;
      cursor: pointer;
      color: #fff;
      font-size: 14px;
      text-align: center;
      line-height: 24px;
    }
    .forward {
      width: 24px;
      height: 24px;
      background: #4056cc;
      margin: 0 5px;
      cursor: pointer;
      color: #fff;
      font-size: 14px;
      text-align: center;
      line-height: 24px;
      transform: rotate(180deg);
    }
    .prev {
      width: 19px;
      height: 34px;
      background: #4056cc;
      margin: 0 5px;
      cursor: pointer;
      color: #fff;
      font-size: 16px;
      text-align: center;
      line-height: 34px;
    }
    .time-ticp-wrap {
      width: 420px;
      .time-ticp {
        width: 420px;
        height: 34px;
        display: flex;
        justify-content: flex-start;
        align-items: flex-end;
        .item-wrap {
          cursor: pointer;
          .name1 {
            margin-right: 5px;
            border-left: 1px solid #ddebff;
            padding-left: 5px;
            padding-bottom: 2px;
          }
          .name2 {
            height: 10px;
            margin-right: 5px;
            border-left: 1px solid #ddebff;
          }
          .item {
            width: 35px;
            padding-left: 5px;
            background: #ddebff;
            margin-right: 5px;
            border-left: 1px solid #ddebff;
            height: 18px;
            font-size: 14px;
            font-family: Microsoft YaHei-Regular, Microsoft YaHei;
            font-weight: 400;
            color: #242424;
            line-height: 16px;
            &.active {
              background: #ddd964;
            }
          }
        }
      }
    }
    .next {
      width: 19px;
      height: 34px;
      background: #4056cc;
      margin: 0 5px;
      cursor: pointer;
      color: #fff;
      font-size: 16px;
      text-align: center;
      line-height: 34px;
      transform: rotate(180deg);
    }
  }
}

.time-line-wrap[data-left-number='560px'] {
  --left-number-value: 290;
}

.time-line-wrap[data-left-number='450px'] {
  --left-number-value: 290;
}
</style>
